import 'package:flutter/material.dart';
import "package:flutter/animation.dart";
import 'dart:math' as math;

class MyAppBar extends StatefulWidget implements PreferredSizeWidget {
  final Function onShowPopHandler;
  final Function onClosePopHandler;
  MyAppBar({this.onShowPopHandler, this.onClosePopHandler, Key key})
      : super(key: key);

  @override
  Size get preferredSize {
    return new Size.fromHeight(56.0);
  }

  @override
  MyAppBarState createState() => MyAppBarState();
}

class MyAppBarState extends State<MyAppBar>
    with SingleTickerProviderStateMixin {
  Animation<double> animation;
  AnimationController controller;

  String _currentCom = "长沙数秩信息科技有限公司";

  String direction = 'down';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    controller = new AnimationController(
        duration: const Duration(milliseconds: 200), vsync: this);
    animation = new Tween(begin: 0.0, end: 180.0).animate(controller)
      ..addListener(() {
        setState(() {
          // the state that has changed here is the animation object’s value
        });
      })
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          // controller.reverse();
          direction = "up";
        } else if (status == AnimationStatus.dismissed) {
          direction = "down";
          // controller.forward();
        }
      });
    // controller.forward();
  }

  void updateArrowStatus(name) {
    if (name != null) {
      this.setState(() {
        _currentCom = name;
      });
    }

    if (direction == 'down') {
      controller.forward();
      widget.onShowPopHandler();
    } else {
      controller.reverse();
      widget.onClosePopHandler();
    }
  }

  @override
  Widget build(BuildContext context) {
    return new SafeArea(
      top: true,
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Row(
          children: <Widget>[
            InkWell(
              onTap: () {
                updateArrowStatus(null);
              },
              child: Row(
                children: <Widget>[
                  Text(
                    _currentCom,
                    style:
                        TextStyle(fontWeight: FontWeight.bold, fontSize: 16.0),
                  ),
                  Transform.rotate(
                    angle: math.pi / 180 * animation.value,
                    child: Icon(
                      Icons.keyboard_arrow_down,
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  @override
  dispose() {
    controller.dispose();
    super.dispose();
  }
}
